const express = require("express");
const router = express.Router();
const axios = require('axios')
const https = require('https');
const db = require("../mysql/index");
// 加密
const jwt = require("jsonwebtoken");

const request = axios.create({
  // baseURL: timeOS.url,
  timeout: 15000,

})

const secretKey = require("./confing");
// const secretKey = require("./confing");


//  注册用户

router.post("/newUser", (req, res) => {
  const arr = req.body;

  // 查询语句判断用户是否已经存在
  const zhuceGo = "select userName from users where userName = ?";

  db.query(zhuceGo, arr.userNname, (err, resq) => {
    if (err) return console.log("数据库查询失败");

    if (resq.length !== 0) {
      res.send({code: 201, status: "用户名已存在"});
    }
    // 注册新用户
    else {
      // 插入用户语句
      const charuUser = "insert into users (userName,passWord) values (?,?)";

      //   删除多余的重复密码
      // delete arr.passWordAgn

      db.query(charuUser, [arr.userNname, arr.passWord], (errs, resu) => {
        if (errs) return console.log("数据库查询失败");
        if (resu.affectedRows == 1) {
          res.send({code: 200, status: "注册成功"});
        }
        // if(resu.aff)
      });
    }
  });
});

// 后台登录
router.post('/user/login',(req,res)=>{
  const sqlUrl='select * from houtai_user where userName = ? and userpass = ?'


  db.query(sqlUrl,[req.body.username,req.body.password],(err,ress)=>{

if(err) res.send({
  code: 404,
  message: "数据库查询用户信息失败",
})

if(ress.length!==0){
  // 生成token
  console.log(ress);
  const tokenStr = jwt.sign({id:ress[0].openid}, secretKey.secretKey, {
    expiresIn: secretKey.tokenH,
  });

  res.send({code:200,
  data:tokenStr,
  message:'登录成功！'
})
}else{
  res.send({code:201,
  
    message:'用户名或密码错误'
  })
}
  })
})



// 小程序登录
router.post("/login", (req, lres) => {


let wx={
  appid:'	wxb5359ac459d03e0a',
  AppSecret:'984a278393af8205bbc402564cb33505'
}
// 向微信服务器发送请求，获取用户的openid
  request({
    url:`https://api.weixin.qq.com/sns/jscode2session?appid=${wx.appid}&secret=${wx.AppSecret}&js_code=${req.body.code}`
   , method:'get',

  }).then(({data})=>{
 
    const sqlurl = "select * from user where openid =?";
db.query(sqlurl,data.openid,(err,res)=>{
  if(err) return console.log('数据库查询失败');
console.log(res.length);
  // 不存在用户
  if(res.length == 0){
     // 插入用户语句
     const charuUser = "insert into user (openid) values (?)";
     db.query(charuUser,data.openid,(errs,ress)=>{
if(err) return console.log("新用户插入失败");

   if(ress.affectedRows==1){

    // 生成token
    const tokenStr = jwt.sign({id:data.openid}, secretKey.secretKey, {
            expiresIn: secretKey.tokenH,
          });

          lres.send({code:200,
          token:tokenStr,
        status:'用户登录成功'})
   }})
  }
  // 这是存在用户 用户已经登陆过了
  if(res.length !== 0){
     // 生成token
     const tokenStr = jwt.sign({id:data.openid}, secretKey.secretKey, {
      expiresIn: secretKey.tokenH,
    });
    lres.send({code:200,
      token:tokenStr,
    status:'用户登录成功'})
  }
})
  })

  const arr = req.body;


});


router.post("/findFriends",(req,res)=>{

console.log(req.body);
    const yong="select userName,passWord,userHead,id from users where userName like ?"

    db.query(yong,`${req.body.userName}%`,(err,ress)=>{

   
// 未查询到
        if(ress.length==0){

            res.send({
            code:201,

                status:'该用户不存在'
            })
        }else if(ress.length!==0){

            res.send({
                code:200,
                data:ress,
                status:"查询成功"
            })
        }
    })
   
})

// 查询好友接口
router.post("/findFriends",(req,res)=>{

console.log(req.body);
    const yong="select userName,passWord,userHead,id from users where userName like ?"

    db.query(yong,`${req.body.userName}%`,(err,ress)=>{

   
// 未查询到
        if(ress.length==0){

            res.send({
            code:201,

                status:'该用户不存在'
            })
        }else if(ress.length!==0){

            res.send({
                code:200,
                data:ress,
                status:"查询成功"
            })
        }
    })
   
})
module.exports = router;
